<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <script>
    // Function.prototype.myBind = function (context) {
    //   const self = this;
    // //   提取bind的参数
    //   const bindArgs = Array.prototype.slice.call(arguments, 1);

    //   return function () {
    //     // 提取call的参数
    //     const callArgs = Array.prototype.slice.call(arguments);
    //     // 判断是不是new调用
    //     if (this instanceof self) {
    //       // 通过new调用药指向实例
    //       return self.apply(this, [...bindArgs, ...callArgs]);
    //     } else {
    //       // 普通调用 绑定context
    //       return self.apply(context, [...bindArgs, ...callArgs]);
    //     }
    //   };
    // };

    Function.prototype.myBind = function (context) {
      const _this = this;

      const bindArgs = [].slice.call(arguments, 1);

      return function () {
        const callArgs = [].slice.call(arguments);

        if (this instanceof _this) {
          return _this.apply(this, [...bindArgs, ...callArgs]);
        } else {
          return _this.apply(context, [...bindArgs, ...callArgs]);
        }
      };
    };

    function greet(message) {
      console.log(`${message}, ${this.name}`);
    }

    const person = { name: 'Alice' };
    const greetPerson = greet.myBind(person, 'Hello');

    greetPerson(); // 输出: "Hello, Alice"

    // 测试 new 调用
    function Animal(type) {
      this.type = type;
      console.log(`I'm a ${this.type}, my name is ${this.name}`);
    }

    const Dog = Animal.myBind({ name: 'Buddy' }, 'Dog');
    new Dog(); // 输出: "I'm a Dog, my name is Buddy"
  </script>
  <body></body>
</html>
